﻿using System;
using System.Collections.Generic;

namespace Orz.Framework.Core
{
    /// <summary>
    /// Manage singleton instances.
    /// </summary>
    public static class SingletonManager
    {
        /// <summary>
        /// The struct to cache the instances by type.
        /// </summary>
        static Dictionary<Type, object> cache = new Dictionary<Type, object>();

        /// <summary>
        /// Gets the singleton instance.
        /// </summary>
        /// <typeparam name="T">The type of instance.</typeparam>
        /// <param name="args">The args.</param>
        /// <returns></returns>
        public static T GetInstance<T>(params object[] args)
        {
            Type type = typeof(T);
            lock (type)
            {
                if (!cache.ContainsKey(type))
                {
                    T instance = (T)Activator.CreateInstance(type, args);
                    cache.Add(type, instance);
                }
                return (T)cache[type];
            }
        }
    }
}
